//
//  KABMallMyShopVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/21.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMallMyShopVC.h"
#import "KABMallProductCCell.h"
#import "KABMyShopHeaderCRView.h"
#import "KABModel.h"
#import "KABMallProDetailVC.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "GlobalHeader.h"
#import <UINavigationBar+Awesome.h>
#import "KABRCIMChatVC.h"
#import "ThemeManager.h"
#import "KABHomepageVC.h"

@interface KABMallMyShopVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, KABMallHeaderCRViewDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic) UIBarButtonItem *colShopItemNormal;
@property (strong, nonatomic) UIBarButtonItem *colShopItemSel;
@property (strong, nonatomic) UIBarButtonItem *customerServiceItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (nonatomic, strong) KABMallShopDetail *shopDetail;

@end

static NSString *const kReuseCellId = @"KABMallProductCCell";
static NSString *const kReuseHeaderId = @"KABMyShopHeaderCRView";
static NSInteger const kRequestCosplayListSize = 20;

@implementation KABMallMyShopVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"店铺";
    
    [self.navigationItem setRightBarButtonItems:@[self.colShopItemNormal, self.customerServiceItem]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0);
    
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    UINib *cRViewNib = [UINib nibWithNibName:kReuseHeaderId bundle:nil];
    [self.collectionView registerNib:cRViewNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseHeaderId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    // 下拉刷新
//    self.collectionView.mj_header = self.mj_header;
    self.collectionView.mj_footer = self.mj_footer;
    // 请求数据
//    [self.collectionView.mj_header beginRefreshing];
    [self requestProductListWithHeader:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.collectionView.delegate = self;
    [self scrollViewDidScroll:self.collectionView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.collectionView.delegate = nil;
    [self.navigationController.navigationBar lt_reset];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.shopDetail.product_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABMallProductCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.item < self.shopDetail.product_list.count) {
        [cell configViewWithProductItem:self.shopDetail.product_list[indexPath.item]];
    }
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        KABMyShopHeaderCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseHeaderId forIndexPath:indexPath];
        [header configViewWithShopDetInfo:self.shopDetail.shop_detail];
        header.delegate = self;
        return header;
    }
    
    return nil;
}

#pragma mark - <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGFloat width = CGRectGetWidth(self.view.bounds);
    CGFloat height = width * 300.0 / 375.0 + 50.0;
    return CGSizeMake(width, height);
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 6.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*14 - 10) / 2.0;
    CGFloat height = width * 257.0 / 169.0;
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    KABMallProDetailVC *vc = [[KABMallProDetailVC alloc] init];
    vc.proItem = self.shopDetail.product_list[indexPath.item];
    [self showViewController:vc sender:nil];
}

//- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
//    if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMyShopHeaderCRView *headerView = (KABMallHeaderCRView *)view;
//        [headerView bannerViewStartScroll];
//    }
//}
//
//- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
//    if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABMyShopHeaderCRView *headerView = (KABMallHeaderCRView *)view;
//        [headerView bannerViewStopScroll];
//    }
//}

#pragma mark - KABMallHeaderCRViewDelegate
- (void)kABMyShopHeaderCRView:(KABMyShopHeaderCRView *)crView portraitTapped:(UIImageView *)imgView {
    KABHomepageVC *hpVC = [[KABHomepageVC alloc] init];
    hpVC.user_id = self.shopDetail.shop_detail.shop_owner_id;
    hpVC.user_name = self.shopDetail.shop_detail.shop_owner_name;
    [self showViewController:hpVC sender:nil];
}

#pragma mark - UIScrollViewDelegate
#define NAVBAR_CHANGE_POINT 300
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //    UIColor * color = [UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1];
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat changeHeight = width * 300.0 / 375.0 - 64.0*2;
    
//    UIColor *color = [UIColor blackColor];
    UIColor *color = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerNavBgColor];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > changeHeight) {
        CGFloat alpha = MIN(1, 1 - ((changeHeight + 64 - offsetY) / 64));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
    }
}

#pragma mark - event response
- (void)shopColBtnTapped:(UIBarButtonItem *)barBtn {
    self.shopDetail.shop_detail.is_collected = !self.shopDetail.shop_detail.is_collected;
    UIBarButtonItem *colBarItem = self.shopDetail.shop_detail.is_collected ? self.colShopItemSel : self.colShopItemNormal;
    [self.navigationItem setRightBarButtonItems:@[colBarItem, self.customerServiceItem]];
    [self requestShopCollectWithShopId:self.shopDetail.shop_detail.shop_id
                           isCollected:self.shopDetail.shop_detail.is_collected];
}

- (void)serviceBtnTapped:(UIBarButtonItem *)barBtn {
    //未登录是不能够聊天的
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    NSString * shopOwnerId = [NSString stringWithFormat:@"%zd", self.shop_owner_id];
    KABRCIMChatVC *chat = [[KABRCIMChatVC alloc] initWithConversationType:ConversationType_PRIVATE targetId:shopOwnerId];
    chat.title = self.shopDetail.shop_detail.shop_name;
    [self showViewController:chat sender:nil];
}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.shopDetail.totalLoad) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.collectionView.mj_footer resetNoMoreData];
    }
    
    self.navigationItem.title = self.shopDetail.shop_detail.shop_name;
    UIBarButtonItem *colBarItem = self.shopDetail.shop_detail.is_collected ? self.colShopItemSel : self.colShopItemNormal;
    [self.navigationItem setRightBarButtonItems:@[colBarItem, self.customerServiceItem]];
    
    [self.collectionView reloadData];
}

- (void)collectionViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.collectionView.mj_header endRefreshing];
    } else {
        [self.collectionView.mj_footer endRefreshing];
    }
}

- (void)collectionViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestProductListWithHeader:isHeader];
}

- (KABMallShopDetail *)shopDetailWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.shopDetail;
    }
    
    KABMallShopDetail *temp = [KABMallShopDetail yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.shopDetail;
    }
    
    if (AddMore && self.shopDetail) {
        [self.shopDetail addMoreWithData:temp];
    } else {
        self.shopDetail = temp;
    }
    return self.shopDetail;
}

#pragma mark - network request
- (void)requestProductListWithHeader:(BOOL)isHeader {
    MBProgressHUD *hud = isHeader ? [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES] : nil;
    
    NSInteger startIndex = isHeader ? 0 : self.shopDetail.product_list.count;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(startIndex) forKey:@"index"];
    [pars setObject:@(kRequestCosplayListSize) forKey:@"size"];
    [pars setObject:@(self.shop_owner_id) forKey:@"shop_owner_id"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"visitor_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineShop] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求商品列表返回：%@", responseObject);
        [self collectionViewEndRefresh:isHeader];
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self shopDetailWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求商品列表失败：%@", error);
        [self collectionViewEndRefresh:isHeader];
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestShopCollectWithShopId:(NSInteger)shopId isCollected:(BOOL)isCollected {
    // 收藏必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"shop_id" : @(shopId),
                           @"is_collected" : isCollected ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiShopCollected] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Shop收藏返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            self.shopDetail.shop_detail.is_collected = !isCollected;
            [self refreshWholeView];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Shop收藏失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

- (UIBarButtonItem *)colShopItemNormal {
    if (!_colShopItemNormal) {
        _colShopItemNormal = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_shop_col"] style:UIBarButtonItemStylePlain target:self action:@selector(shopColBtnTapped:)];
    }
    return _colShopItemNormal;
}
- (UIBarButtonItem *)colShopItemSel {
    if (!_colShopItemSel) {
        _colShopItemSel = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_shop_col_sel"] style:UIBarButtonItemStylePlain target:self action:@selector(shopColBtnTapped:)];
    }
    return _colShopItemSel;
}
- (UIBarButtonItem *)customerServiceItem {
    if (!_customerServiceItem) {
        _customerServiceItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mall_cus_service_baise"] style:UIBarButtonItemStylePlain target:self action:@selector(serviceBtnTapped:)];
    }
    return _customerServiceItem;
}

@end
